package controllers;

import play.*;
import play.cache.Cache;
import play.data.validation.Valid;
import play.db.jpa.Blob;
import play.i18n.Lang;
import play.libs.Crypto;
import play.libs.Images;
import play.libs.Mail;
import play.libs.OAuth2;
import play.libs.WS;
import play.mvc.*;
import play.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

import org.apache.commons.io.IOUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import com.google.gson.JsonObject;

import models.*;
public class Application extends Controller {
	
	   public static void index2() {
	    	
	    	String lang = Lang.get();
	    	Lang.change(lang);
	    	
	    	  List<Usuario> contacts = Cache.get("contacts", List.class);
	    	  if(contacts == null) {
	    		  contacts = Usuario.all().fetch();
	              Cache.set("contacts", contacts, "30mn");
	          }
	        render(contacts);
	    }
	        
	   
	   public static void login(String username, String password) {
	    	Crypto a = new Crypto();
	        String senha = a.encryptAES(password);
	    	Usuario user = Usuario.find("byUsu_nomeAndUsu_senha", username, senha).first();
	        if(user != null) {
	            session.put("username", user.usu_nome);
	           Timeline.index();         
	        }
	        // Oops
	        flash.put("username", username);
	        flash.error("Login failed");
	        index2();
	    }
	   
	   static Usuario connected() {
	        if(renderArgs.get("user") != null) {
	        	Logger.info("chgou no lugar certo " );
	            return renderArgs.get("user", Usuario.class);
	        }
	        String username = session.get("username");
	        if(username != null) {
	            return Usuario.find("byUsu_nome", username).first();
	        } 
	        
	        Logger.info("deu foi merda " );
	        return null;
	    }
	   
	   
	   @Before
	    static void addUser() {
		   Usuario user = connected();
	         
	        if(user != null) {
	            renderArgs.put("user", user);
	        }
	    }
	   
	   
    public static void logout() {
        session.clear();
        index2();
    }
    
    public static void registrar() {
       
        render();
    }
    
    public static void registrar(String erro ) {
        
        render(erro);
    }
    
    public static void recuperarsenha() {
        
        render();
    }
    
    public static void sendPassword() {
    	String id = params.get("email", String.class);
    	SimpleEmail email = new SimpleEmail();
    	try {
			email.setFrom("odilionoronha@gmail.com");
			email.addTo(id);
	    	email.setSubject("Nova senha");
	    	email.setMsg("Nova senha ainda em desenvolvimento");
	    	Mail.send(email); 
		} catch (EmailException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	index2();
    	
    }
    public static void saveUser( Usuario usuario, String verifyPassword, String verifyEmail) {
       //validation.required(verifyPassword).message("Campo Obrigatorio");
       //validation.equals(verifyPassword, user.usu_senha).message("Seu password não confere");
       // validation.required(verifyEmail).message("Campo Obrigatorio");
       // validation.equals(verifyEmail, user.email).message("Seu email não confere");
      
        
      /*  File f = user.usu_ima.getFile();
       String s = user.usu_ima.type();
        File newFile = new File(user.usu_nome+user.usu_senha); // create random unique filename here
        Images.resize(f, newFile, 100, -1);
        FileInputStream a = null;
		try {
			a = new FileInputStream(newFile);
		
        user.usu_ima.set(a, s); 
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
    	if (Usuario.find("byUsu_nome", usuario.usu_nome).first() == null){
        Crypto a = new Crypto();
        String senha = a.encryptAES(usuario.usu_senha);
        usuario.usu_senha = senha;
        Blob usu_ima = usuario.usu_ima ;
        usuario.save();
        if (usu_ima != null){ 
			
        File outputFile = Play.getFile("/public/avatar/" + usuario.usu_nome+usuario.usu_codigo + ".jpg");
        Images.resize(usu_ima.getFile(), outputFile, 100, -1);
        usuario.usu_caminho_ima = "http://scriptor.net.br/public/avatar/" + usuario.usu_nome+usuario.usu_codigo + ".jpg";
        usuario.save();
        		               //  IOUtils.copy(iStream, new FileOutputStream(outputFile));
		
        }
        session.put("username", usuario.usu_nome);
        index2();
    	}
    	else{
    		registrar("login já esxiste!");
    	}
    }
    
    
    public static void alterUser(@Valid Usuario user) {
    	Blob usu_ima = user.usu_ima ;
         user.save();
         Pessoa pessoa = new Pessoa();
         pessoa.pes_nome = user.usu_nome;
         FileInputStream iStream;
         if (usu_ima != null){ 
 		try {
 			iStream = new	FileInputStream(usu_ima.getFile());
 		
         File outputFile = Play.getFile("/public/avatar/" + user.usu_nome+user.usu_codigo + ".jpg");
         Images.resize(user.usu_ima.getFile(), outputFile, 100, -1);
         user.usu_caminho_ima = "http://scriptor.net.br/public/avatar/" + user.usu_nome+user.usu_codigo + ".jpg";
         user.save();
         		                
 		} catch (FileNotFoundException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		} catch (IOException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
         }
         session.put("username", user.usu_nome);
         Timeline.index();  
     }
    public static void userPhoto(int id) {
    	   final Usuario user = Usuario.findById(id);
    	   notFoundIfNull(user);
    	   response.setContentTypeIfNotSet(user.usu_ima.type());
    	   renderText(user.usu_caminho_ima);
    	}
    
    public static void mudarIdioma(int id) {
    	if (id == 1)
    	Lang.change("en");
    	else if (id == 2)
    		Lang.change("pt");
    	else if (id == 3)
    		Lang.change("sp");
    	 if(renderArgs.get("user") != null) {
    		 Timeline.index();  
         }
    	 
    }
    
    
    
    public static void privacypolicy() {
    	render();
    }
    
    
    
    public static OAuth2 FACEBOOK = new OAuth2(
            "https://graph.facebook.com/oauth/authorize",
            "https://graph.facebook.com/oauth/access_token",
            "291857904312787",
            "e79d4e7b2450e7cd485317763353d1d1"
    );

    public static void index(Usuario u) {
        
        Logger.info("nuloooo " );
        JsonObject me = null;
        JsonObject outro = null;
        String a = null;
        Logger.info("usuario  " + u.usu_codigo);
        if (u != null && u.access_token != null) {


            me = WS.url("https://graph.facebook.com/me?access_token=%s", WS.encode(u.access_token)).get().getJson().getAsJsonObject();

            
           a = WS.url("http://graph.facebook.com/"+me.get("id").toString().replaceAll("\"", "")+"/picture").url;
           u.usu_nome_completo = me.get("name").toString().replace("\"", "");
           u.usu_nome = me.get("first_name").toString().replace("\"", "");
           //u.usu_email = me.get("email").toString();
           u.usu_caminho_ima = a;
           if (Usuario.find("byUsu_nome", u.usu_nome).first() == null){
           u.save();
           }
           session.put("username", u.usu_nome);
          // renderArgs.put("username", u.usu_nome);
           //session.put("user", u);
           //renderArgs.put("user", u);
           Logger.info("dentro do info  " + u.access_token);
           Timeline.index();      
            
           
        }
        Logger.info("code repossss " + u.access_token);
        render(me,outro,a);
    }

    public static void auth() {
        if (OAuth2.isCodeResponse()) {
			Usuario u = new Usuario();
            OAuth2.Response response = FACEBOOK.retrieveAccessToken(authURL());
            u.access_token = response.accessToken;
            
            //u.save();
            session.put("user", u);
            renderArgs.put("user", u);
            
            Logger.info("token da merda do usuario "+ u.access_token );
            index(u);
        }
        FACEBOOK.retrieveVerificationCode(authURL());
    }

   

    static String authURL() {
        return play.mvc.Router.getFullUrl("Application.auth");
    }

   

}